<?php


namespace App\Service\OpenShop\Feishu;


use App\Enums\OpenShop\InvestmentPromotion\MainProcessEnum;
use App\Exceptions\Custom\CustomHttpResponseException;
use App\Http\Middleware\OpenShop\UserPermissionAuth;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;

class MessageSendService extends BaseService
{

    public string $text;
    public string $tag;
    public string $receiveType      = 'user_id';
    public string $messageType      = 'interactive';
    public array  $urlData          = [];
    public array  $receiveFeiShuIds = [];
    private string $module = UserPermissionAuth::MODULE_OPEN_SHOP;

    public array $field = [];

    public function setField(string $name, string $value)
    {
        $this->field[] = [
            'name'  => $name,
            'value' => $value
        ];
        return $this;
    }

    /**
     * @param array $fields
     * @return $this
     */
    public function batchSetField(array $fields = []): MessageSendService
    {
        if(!empty($fields)){
            collect($fields)->each(function($v){
                array_push($this->field, [
                    "name" => $v["name"] ?? "",
                    "value" => $v["value"] ?? ""
                ]);
            });
        }
        return $this;
    }

    public function setModule(string $module)
    {
        $this->module = $module;
        return $this;
    }

    public function setText(string $text)
    {
        $this->text = $text;
        return $this;
    }

    public function setTag(string $tag)
    {
        $this->tag = $tag;
        return $this;
    }

    public function setUrl(string $url, string $content = '查看订单')
    {
        if (!empty($url)) {
            $this->urlData['url']     = $url;
            $this->urlData['content'] = $content;
        }
        return $this;
    }

    public function setUrlData(array $urlData)
    {
        $this->urlData = $urlData;
        return $this;
    }

    public function setReceiveFeiShuIds(array $ids)
    {
        $this->receiveFeiShuIds = array_values(array_unique($ids));
        return $this;
    }

    public function send()
    {
        $template = $this->genSendTemplate();
        foreach ($this->receiveFeiShuIds as $feishuId) {
            Log::info("{$feishuId}-{$this->text} 成功发送飞书消息：" . json_encode($template, JSON_UNESCAPED_UNICODE));
            self::sendMessage($feishuId, $this->receiveType, $template, $this->messageType, $this->module);
        }
    }

    private function genSendTemplate()
    {
        $template = [
            'elements' => []
        ];

        $element = [
            'tag' => 'div',
        ];

        if (!empty($this->text)) {
            $element['text'] = [
                'tag'     => 'lark_md',
                'content' => $this->text,
                'lines'   => 1,
            ];
        }

        if (!empty($this->field)) {
            foreach ($this->field as $field) {
                $element['fields'][] = [
                    'is_short' => false,
                    'text'     => [
                        'tag'     => 'lark_md',
                        'content' => vsprintf("%s：%s", [$field['name'], $field['value']])
                    ]
                ];
            }
        }
        $template['elements'][] = $element;

        if (!empty($this->urlData)) {
            $urlAction              = [
                "tag"     => 'action',
                "actions" => [
                    [
                        'tag'  => 'button',
                        'text' => [
                            'tag'     => 'plain_text',
                            'content' => $this->urlData['content'],
                        ],
                        'url'  => $this->urlData['url'],
                        'type' => "primary",
                    ]
                ]
            ];
            $template['elements'][] = $urlAction;
        }

        return $template;
    }
}
